package nature.nano.util.pipe;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.Stack;

import nature.nano.component.PrimaryPipe;
import nature.nano.component.Strings;
import nature.nano.iface.Props;

public class TimeCounter extends PrimaryPipe {

	private static SimpleDateFormat format = new SimpleDateFormat(Strings.longTimeFormat);
	
	private class Data {
		String name;
		Date begin;		
		Date end;
		Data(String name) {
			this.name = name;
			begin = new Date();
		}
	}
	
	private Stack<Data> stack = new Stack<Data>();
	private Set<String> nodes = new HashSet<String>();
	
	public TimeCounter() {
		slots(Strings.output);
		props(Strings.tags);
	}

	@Override
	protected void initialize() {
		String tags = prop(Strings.tags);
		for (String tag : tags.split(Strings.comma)) {
			nodes.add(tag);
		}			
	}
	
	@Override
	public void anBegin(String type, Props props) {
		if (stack.size() == 0 || nodes.contains(type)) {
			output().onBegin(type, props);
		}
		stack.push(new Data(type));
	}

	@Override
	public void anEnd(String type) {
		Data data = stack.pop();
		data.end = new Date();
		if (stack.size() == 0 || nodes.contains(type)) {
			output(
				Strings.elapsedTime,
				Strings.millisecond, Long.toString(data.end.getTime() - data.begin.getTime()),
				Strings.begin, format.format(data.begin),
				Strings.end, format.format(data.end));			
			output().onEnd(type);
		}
	}

}
